package hfut.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hfut.example.common.R;
import hfut.example.dto.SetmealDto;
import hfut.example.entity.Category;
import hfut.example.entity.Setmeal;
import hfut.example.entity.SetmealDish;
import hfut.example.service.CategoryService;
import hfut.example.service.SetmealDishService;
import hfut.example.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true/*表示删除该分类下所有数据*/)
    @ApiOperation(value = "新增套餐")
    public R<String>  save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Setmeal::getName,name).orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            //获取菜品对应的ID
            Long categoryId = item.getCategoryId();
            //根据Id获得Category
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //获取菜品名称
                String categoryName = category.getName();
                //将菜品类型的名称注入
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @CacheEvict 将一条或多条数据从缓存中删除
     * @param ids @RequestParam(required = false)使得能用List集合接收参数
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true/*表示删除该分类下所有数据*/)
    public R<String> delete(@RequestParam(required = false) List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 停售与起售
     * @param status @PathVariable表示路径中的变量
     * @param ids  @RequestParam(required = false) 能用List接收变长参数
     * @return 返回不同
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true/*表示删除该分类下所有数据*/)
    public R<String> status(@PathVariable int status,@RequestParam(required = false)List<Long> ids){
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.in(Setmeal::getId,ids).set(Setmeal::getStatus,status);
        setmealService.update(updateWrapper);
        if(status==0){
            return R.success("停售成功");
        }else {
            return R.success("启售成功");
        }

    }

    /**
     * 修改菜品时回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        Setmeal setmeal = setmealService.getById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(setmealDishes);

        return R.success(setmealDto);
    }

    /**
     * 更新套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true/*表示删除该分类下所有数据*/)
    public R<String> update(@RequestBody SetmealDto setmealDto){

        return setmealService.updateWithSetmealDish(setmealDto);
    }

    /**
     * 套餐展示
     * @Cacheable 若有缓存则无需查数据库;value表示一类缓存,key则是redis中的key
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(setmeal.getCategoryId() !=null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);

    }

}
